package com.LeeCode;

import java.util.HashMap;

/**
 * 从链表中删去总和值为零的连续节点
 */

public class Code1171 {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, -3, -2};
        ListNode head = Utils.arrayToListNode(arr);
        Utils.printListNode(new Code1171().removeZeroSumSublists(head));
    }

    public ListNode removeZeroSumSublists(ListNode head) {
        ListNode dummy = new ListNode(0, head), cur = dummy;
        HashMap<Integer, ListNode> map = new HashMap<>();

        int preSum = 0;
        while (cur != null) {
            preSum += cur.val;
            map.put(preSum, cur);
            cur = cur.next;
        }
        preSum = 0;
        cur = dummy;
        while (cur != null) {
            preSum += cur.val;
            cur.next = map.get(preSum).next;
            cur = cur.next;
        }

        return dummy.next;
    }
}
